from flask import Flask, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate
from datetime import datetime
from app.config import Config, config  # 导入Config类和config字典
import os
import jinja2

# 创建扩展实例
db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.login_message = '请先登录!'
login_manager.login_message_category = 'info'

def create_app(config_name=None):
    app = Flask(__name__)
    
    # 根据环境变量确定使用哪个配置
    if not config_name:
        config_name = os.getenv('FLASK_ENV', 'production')
    
    # 使用配置字典选择配置类
    app.config.from_object(config.get(config_name, config['default']))
    
    # 调用配置类的init_app方法进行特定初始化
    config[config_name].init_app(app)
    
    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    
    # 注册蓝图
    from app.routes.main import main
    from app.routes.auth import auth as auth_blueprint
    from app.routes.user import user
    from app.routes.blind_box import blind_box as blind_box_blueprint
    from app.routes.supermarket import supermarket as supermarket_blueprint
    from app.routes.order import order
    from app.routes.analytics import analytics as analytics_blueprint
    from app.routes.api import api_bp
    
    app.register_blueprint(main)
    app.register_blueprint(auth_blueprint)
    app.register_blueprint(user)
    app.register_blueprint(blind_box_blueprint)
    app.register_blueprint(supermarket_blueprint)
    app.register_blueprint(order)
    app.register_blueprint(analytics_blueprint)
    app.register_blueprint(api_bp)
    
    # 注册自定义过滤器
    @app.template_filter('nl2br')
    def nl2br_filter(text):
        if text:
            return jinja2.utils.markupsafe.Markup(text.replace('\n', '<br>'))
        return ''
    
    @app.context_processor
    def inject_now():
        return {'now': datetime.now()}
    
    @app.context_processor
    def inject_pending_applications():
        def get_pending_count():
            # 导入模型避免循环导入
            from app.models.supermarket_application import SupermarketApplication
            
            try:
                # 只有已登录用户才获取数据
                from flask_login import current_user
                if current_user.is_authenticated:
                    return SupermarketApplication.query.filter_by(status='pending').count()
                return 0
            except Exception:
                return 0
        
        return {'pending_application_count': get_pending_count()}
    
    # 添加图片重定向路由
    @app.route('/images/boxes/<filename>')
    def box_image(filename):
        return send_from_directory(os.path.join(app.static_folder, 'images', 'boxes'), filename)
    
    return app 